import { Container, DisplayObject, Graphics, InteractionEvent, Point, Sprite, Text, Ticker } from 'pixi.js';
import { IRouter, back, to } from '../utils/router';
import { ox, OSprite, OContainer, OText } from 'oixi2';
import { HEIGHT, WIDTH, COLOR_RED } from '../game/constant';
import { layout } from '../utils/layout';
import { ceil, floor, getRandomNum, random, scope, shuffleArray } from '../utils/math';
import { LevelItem, XLevelItem } from './LevelItem';
import { DetailItem, XDetailItem } from './DetailItem';
import { Ease, tween } from '../utils/tween';
import storage from '../game/storage';
import { WorldFail, XWorldFail } from './WorldFail';
import { BelongType, MonsterEffect, StageType, TriggerType, TurnType } from '../model/types';
import { getCardById } from '../levels/cardInfo';
import { fail } from 'assert';
import { getConfigHeroById } from '../game/app';


export default function () {
  let rowCount = 5
  let cardWidth = 120
  let cardHight = 200
  let dropX = 999
  let dropY = 888


  return ox(new A, null, () => [
    OText('#tip x=75 y=14', { fill: COLOR_RED, fontSize: 40 }),
    OText('#enemyCardText x=75 y=120', { fill: COLOR_RED, fontSize: 30 }),
    OSprite('y=' + (HEIGHT - 285) + ' @touchstart=closePopUp', 'bg_level.png'),
    //攻击按钮
    layout(OSprite('#btnPlay @pointertap=doAttack y=' + (HEIGHT - 120),

      'btn_lang_a.png', [
      OText('#attackTitle x=5 y=14 ', { fill: COLOR_RED, fontSize: 40 })
    ])).centerX(0).centerY(80).target,

    //结束回合
    layout(OSprite('#btnEndTurn @pointertap=endTurn y=' + (HEIGHT - 120),

      'btn_lang_a.png', [
      OText('#endTurnTitle x=5 y=14', { fill: COLOR_RED, fontSize: 40 })
    ])).centerX(150).centerY(80).target,
    //energy_bg.png
    OSprite('#btnLife y=15 x=' + (WIDTH - 130), 'btn_life.png', [
      OText('#life1 x=75 y=14', { fill: COLOR_RED, fontSize: 40 })
    ]),
    OSprite('#btnEneger  y=15 x=50', 'energy_bg.png', [
      OText('#enmeyEnergyText x=15 y=14', { fill: COLOR_RED, fontSize: 40 })
    ]),
    layout(OContainer([
      OSprite('#playerbtnEneger  y=95 x=50', 'energy_bg.png', [
        OText('#playerEnergyText x=15 y=14', { fill: COLOR_RED, fontSize: 40 })
      ]),
    ])).centerY(-100).target,
   
    //玩家牌数
    layout(OContainer([
      OText('#playerCardText x=75 y=120', { fill: COLOR_RED, fontSize: 30 }),
    ])).centerY(-100).target,
    //item2
    layout(OContainer([
      OContainer('#items2 @pointertap=onSelectLevel x=20', scope(0, 5).map(n => {
        let x = n % rowCount * 100
        let y = floor(n / rowCount) * 120
        return LevelItem(`x=${x} y=${y}  width=${cardWidth} height=150`)
      }))
    ])).centerY(-200).target,

    //item3
    layout(OContainer([

      OContainer('#items3 @pointertap=onSelectLevel  x=20', scope(0, 5).map(n => {
        let x = n % rowCount * 100
        let y = floor(n / rowCount) * 120
        return LevelItem(`x=${x} y=${y} width=${cardWidth} height=150 @pointertap=onSelectCard @touchstart=onDragStart @pointerdown=pressing @pointerup=endPressing @touchmove=onDrag @touchend=onDragEnd`)
      }))
    ])).centerY(200).target,

    //item4
    layout(OContainer([

      OContainer('#items4 @pointertap=onSelectLevel  x=20', scope(0, 5).map(n => {
        let x = n % rowCount * 100
        let y = floor(n / rowCount) * 120
        return LevelItem(`x=${x} y=${y} width=${cardWidth} height=${cardHight}  @touchstart=onDragStart @touchmove=onDrag @touchend=onDragEnd @pointerdown=pressing @pointerup=endPressing `)
      }))
    ])).centerY(400).target,


    OSprite('#btnLife  y=' + (HEIGHT - 140) + ' x=' + (WIDTH - 130), 'btn_life.png', [
      OText('#life x=75 y=14', { fill: COLOR_RED, fontSize: 40 })
    ]),
    LevelItem(`#dragBox x=${dropX} y=${dropY} anchor=0.5 width=${cardWidth} height=150`),
    LevelItem(`#bullet x=${dropX} y=${dropY} anchor=0.5 width=50 height=50`),
    DetailItem(`#detailBox x=${WIDTH / 2 - 125} y=${HEIGHT / 2 - 125}  width=350 height=450 visible=false`),
    layout(OContainer('#endPanel', [

      OSprite('#endPanelPic  width=500 height=500', 'back_item.png', [
        OText('#endText x=20 y=0', { fill: COLOR_RED, fontSize: 30 })
      ]),
      OSprite('@pointertap=restartGAme x=32 y=395', 'btn_replay.png', [
        // OSprite('#iconAd x=20 y=20', 'video.png'),
        OText('#btnlabel anchor=0.5 x=215 y=40', { fontSize: 30 })
      ]),
    ])).centerX(0).centerY(0).target,
    //tip
    layout(OSprite('#tipBtn @pointertap=onPlay width=300 alpha=0 y=' + (HEIGHT - 120),

      'btn_lang_a.png', [
      OText('#tipTitle x=5 y=14 ', { fill: COLOR_RED, fontSize: 30 })
    ])).centerX(0).centerY(0).target,

  ])
}

class A extends Container implements IRouter {

 
 
  btnEneger:Sprite = null
  playerbtnEneger:Sprite = null
  tipBtn: Sprite = null
  tipTitle: Text = null
  enmeyEnergyText: Text = null
  playerEnergyText: Text = null
  endPanelPic: Sprite = null
  btnPlay: Sprite = null
  btnBack: Sprite = null
  endPanel: Sprite = null
  btnLife: Sprite = null
  btnLeft: Sprite = null
  btnRight: Sprite = null
  btnEndTurn: Sprite = null
  dragBox: Sprite = null
  btnlabel: Text = null
  endTurnTitle: Text = null
  items1: Container = null
  items2: Container = null
  items3: Container = null
  items4: Container = null
  bullet: Sprite = null
  dragItem: XLevelItem = null
  life1: Text = null
  life: Text = null
  endText: Text = null
  detailBox: XLevelItem = null
  tip: Text = null
  attackTitle: Text = null
  private currentPage: number
  dragging: number = 1
  dragIndex: number = -1
  dragId: number = 0
  playerHp: number = 20
  enemyHp: number = 20
  fail: XWorldFail = null
  isPressing: boolean = false
  pressTime: number = 0
  currentTurn: TurnType = TurnType.Player
  pressItem: XLevelItem = null;
  enemyWasterCArdIds = [] //敌人牌库
  enemyStoracardIds = [1, 1, 2, 2, 3] //敌人牌库
  enmeyHandCardIds = []; //敌人手牌
  playerHandCardIds = []
  playerWAstCarIds = []
  playerStorageCardIs = []
  selectFightItem: XLevelItem = null;
  enemyCardText: Text = null
  playerCardText: Text = null
  enmeyCardNm = 10;
  waitText = '请攻击或上阵卡牌'
  hasDoAction: boolean = false
  kiiledByIndex = -1
  curAttackItem: XLevelItem = null
  enemyChooseItem: XLevelItem = null
  gameStage: StageType = StageType.PlayerAttack
  attackCount:number=0
  playerEnergy:number=1
  enemyEnergy:number=1
  curTurnNum:number=1
  maxHP:number=30
  actived() {
    //console.log(getConfigHeroById(2))
    this.restartGAme()
    this.fail = new XWorldFail();
    //this.endPanel.visible = true
  }

  showTip(content: string) {
    this.tipBtn.alpha = 1
    this.tipTitle.text = content
    // this.tipBtn.width=300
    this.tipBtn.y = HEIGHT - 200
    tween(this.tipBtn).to({ y: (HEIGHT - 500) }, 300, Ease.sineOut).wait(1000).onComplete(() => {
      this.tipBtn.alpha = 0
    })
    // tween(this.tipBtn.alpha).to(1, 300, Ease.backOut).wait(1000).onComplete(()=>{
    //   this.tipBtn.alpha = 0
    // })
  }

  restartGAme() {
    this.curTurnNum = 1
    this.attackTitle.text = "攻击"
    this.endTurnTitle.text = '结束'
    this.playerHandCardIds = [30,30,30,30]
    this.playerStorageCardIs = [2, 2, 2]
    this.playerWAstCarIds = [];
    this.enmeyHandCardIds = [11, 11, 11]
    this.enemyStoracardIds = [11, 11, 1]
    this.enemyWasterCArdIds = []
    this.shuffleCard()
    this.prepareCard()
    this.updateLevelList()
    this.enemyHp = this.maxHP
    this.playerHp = this.maxHP
    this.updatecardNum()
    this.tip.text = this.waitText
    this.btnlabel.text = "重新开始"
    this.endPanel.visible = false
  }

  shuffleCard() {
    let cards = []
    for (let i = 0; i < 30; i++) {
      cards.push(i)
      cards.push(i)
    }
    shuffleArray(cards)
    this.playerStorageCardIs = []
    this.playerHandCardIds = []
    this.enemyStoracardIds = []
    this.enmeyHandCardIds = []
    for (let i = 0; i < 5; i++) {
      this.playerStorageCardIs.push(cards.pop())
      this.playerHandCardIds.push(cards.pop())
      this.enemyStoracardIds.push(cards.pop())
      this.enmeyHandCardIds.push(cards.pop())
    }
  }

  prepareCard() {
    for (let i = 0; i < 5; i++) {
      this.playerStorageCardIs.push(getRandomNum(1, 30));
    }

  }

  updatecardNum() {
    this.playerEnergyText.text = this.playerEnergy.toString()
    this.enmeyEnergyText.text=  this.enemyEnergy.toString()
    this.enemyCardText.text = "手牌数:" + this.enmeyHandCardIds.length + " , 牌库数:" + this.enemyStoracardIds.length + " , 弃牌数:" + this.enemyWasterCArdIds.length
    this.playerCardText.text = "手牌数:" + this.playerHandCardIds.length + " , 牌库数:" + this.playerStorageCardIs.length + " , 弃牌数:" + this.playerWAstCarIds.length
  }

  reactived() {
    this.tip.text = this.waitText
    this.updateLevelList()
  }

  closePopUp() {
    console.log("close")
    this.detailBox.visible = false
  }

  getEtracStr(oriIndex:number){
    let res=0
    this.items3.children.forEach((v,k)=>{
      if(v.id == 30 && k!=oriIndex){
        res+=1
      }
    })
    return res
  }

  updateLevelList() {
    this.life.text = this.playerHp.toString()
    this.life1.text = this.enemyHp.toString()
    // this.btnBack.x = -85
    // tween(this.btnBack).to({ x: 0 }, 300, Ease.sineOut)
    // this.btnLife.x = WIDTH
    this.currentPage = ceil(storage.level / 12)
    this.updateLevelPage()
    this.updateEnemyCardList()
  }

  showDetail(id: number) {
    this.detailBox.visible = true;
    this.detailBox.updateId(this.pressItem.id, true, true)
  }

  onBack() {
    back()
  }

  onPlay() {
    // console.log("玩家攻击")
    //to('World', storage.level)
  }



  onSelectCard(e: InteractionEvent) {
    let target = e.target as XLevelItem
    this.selectFightItem = target

    if (target.parent.name == "items3") {
      target.selected();
    }

  }

  pressing(e: InteractionEvent) {
    let target = e.target as XLevelItem
    this.pressItem = target;
    this.isPressing = true;
  }

  endPressing() {
    this.isPressing = false
  }

  onSelectLevel(e: InteractionEvent) {
    let target = e.target as XLevelItem
    console.log("tId" + target.id)
    if (target.id) {
      if (target.parent.name != 'items3') {
        //this.showDetail(target.id)
      }
    }
  }

  playerTurn(){
    this.hasDoAction = false
    this.attackCount=0
  }

  endTuns() {
    this.currentTurn = this.currentTurn == TurnType.Player ? TurnType.Enemy : TurnType.Player;
    this.tip.text = this.currentTurn == TurnType.Player ? '你的回合' : '敌方回合'
  }

  monsterPlaceCard() {
    //出牌 ，抽牌有牌就攻击
    let ranIndex = getRandomNum(0, this.enmeyHandCardIds.length);

    let id = this.enmeyHandCardIds[ranIndex]
    this.enmeyHandCardIds.splice(ranIndex, 1);

    this.updatecardNum()
    for (let i = 0; i < this.items2.children.length; i++) {
      if (this.items2.children[i].id <= 0) {
        this.items2.children[i].updateId(id)
        let carfInfo = getCardById(id)
        if (carfInfo && carfInfo.triggerType == TriggerType.OnScene) {
          this.currentTurn = TurnType.Enemy
          this.getOneScneEffeat(carfInfo.id)
        }
        return
      }
    }

  }

  doAttack() {
    console.log("atack")
    //1 找到选中卡牌，敌人随机拿卡牌出来
    if (this.hasDoAction) {
      //this.showTip("请结束回合")
      this.detailBox.visible = false
      return
    }
    let playerCArd = getCardById(this.selectFightItem.id);
    this.attackCount++;
    console.log("攻击次数:"+this.attackCount)
    if(playerCArd.monsterEffect && playerCArd.monsterEffect.includes(MonsterEffect.Double) ){
      this.attackCount++;
      console.log("inlucde")
      if(this.attackCount>=2){
        this.hasDoAction = true
      }
    }else{
      this.hasDoAction = true
    }
    
    
    //2 比较大小，攻击力小被消灭（高攻击像地攻击放子弹），攻击力一样，一起死
    this.enemyChooseItem = null
    for (let i = 0; i < this.items2.children.length; i++) {
      //console.log("id" + this.items2.children[i].id)
      if (this.items2.children[i].id > 0) {
        this.enemyChooseItem = this.items2.children[i]
        break
      }
    }

    //
    if (this.enemyChooseItem) {
      //console.log(this.enemyChooseItem.id + '--' + this.selectFightItem.id)
      if (!this.selectFightItem || this.selectFightItem.id <= 0) {
        //玩家没出牌
        this.directAnim(2, false)
      } else {
        let tmp = getCardById(this.selectFightItem.id)
         let enemyChooseItem = this.enemyChooseItem
        // this.items2.children.forEach(v => {
        //   if (v.highlight.visible) {
        //     enemyChooseItem = v;
        //   }
        // })
        //console.log(enemyChooseItem)
        let tmp1 = getCardById(enemyChooseItem.id);
        if (tmp1.strenth > tmp.strenth) {
          console.log("敌人攻击")
          this.doattackAnim(enemyChooseItem, this.selectFightItem)
          this.playerWAstCarIds.push(this.selectFightItem.id)
          this.kiiledByIndex = enemyChooseItem.index
          this.getDefeatEvetn(this.selectFightItem.id)

        } else if (tmp1.strenth == tmp.strenth) {
          console.log("一起攻击")
          this.doattackAnim(enemyChooseItem, this.selectFightItem)
          this.doattackAnim(this.selectFightItem, enemyChooseItem)
          this.getDefeatEvetn(this.selectFightItem.id)
          this.getDefeatEvetn(enemyChooseItem.id)
          this.playerWAstCarIds.push(this.selectFightItem.id)
          this.enemyWasterCArdIds.push(enemyChooseItem.id)
        } else {
          console.log("我方攻击攻击")
          this.doattackAnim(this.selectFightItem, enemyChooseItem)
          this.enemyWasterCArdIds.push(enemyChooseItem.id)

          this.getDefeatEvetn(enemyChooseItem.id)
        }
      }

    } else {
      this.directAnim(2)
    }
    this.playerTurn()
    this.updatecardNum()
  }

  endTurn() {
    this.btnEndTurn.scale.set(1)
    tween(this.btnEndTurn.scale).to({ x: 1.1, y: 1.1 }, 300, Ease.backOut).onComplete(()=>{
      this.btnEndTurn.scale.set(1)
    })
    console.log("怪物出牌")
    this.playerTurn()
    
    this.ruchongMonserTurn()
    this.playerMove()
  }

  async playerMove() {
    //let pathPoint = ''
   // this.currentUnit.moveStep = pArrs.length;
   // cc.log("移动步数:"+this.currentUnit.moveStep)
    for (let item of this.items3.children) {
        //item.visible = false
        console.log(this.getOpponent(item))
        let opp = this.getOpponent(item)
        if(item.id>0){
          if(opp.id>0){
            this.doattackAnim(item,opp)
          }else{
            this.directAnim(item.zIndex,true)
          }
        }
       
        //this.getOpponent(item).visible =  false
        // DataManager.Instance.gridMap[a.x][a.y].redCell.active = true;
        // pathPoint += `[${a.x},${a.y}]->`
        // this.currentUnit.setXY(a.x, a.y)
        // this.currentUnit.node.setPosition(a.x * GRID_SIZE, a.y * GRID_SIZE)
        await this.sleep(0.5);
    }
    // this.currentUnit.setCanMove(false) ;
    // this.clearAllRange()
    

  }

  getOpponent(item:XLevelItem):XLevelItem{
    if(item.parent.name == "items3"){
      return this.items2.children[item.index]
    }else{
      return this.items3.children[item.index]
    }
  }

  sleep(seconds: number) {
    return new Promise((resole) => setTimeout(resole, seconds * 1000));
  }

  ruchongMonserTurn(){
    let num = this.getMonsterFightNum()
    if (num > 0) {
      if (getRandomNum(1, 100) < 50) {
        this.monsterAttack()
      } else {
        this.monsterPlaceCard()
      }
    } else {
      this.monsterPlaceCard()
    }
    this.curTurnNum++
    this.playerEnergy = this.curTurnNum
    this.enemyEnergy = this.curTurnNum
    this.updatecardNum()
  }

  monsterAttack() {
    //2 比较大小，攻击力小被消灭（高攻击像地攻击放子弹），攻击力一样，一起死
    let enemyChooseItem = null
    for (let i = 0; i < this.items2.children.length; i++) {
      //console.log("id" + this.items2.children[i].id)
      if (this.items2.children[i].id > 0) {
        enemyChooseItem = this.items2.children[i]
        //if (target.parent.name == "items3") {

        //}
        break
      }
    }

    //
    if (enemyChooseItem) {

      console.log(enemyChooseItem.id)
      this.enemyChooseItem = enemyChooseItem
      this.enemyChooseItem.selected();
      this.showTip("请选择迎战卡牌" + enemyChooseItem.id)
      this.gameStage = StageType.PlayerSelectFightCard



    } else {
      this.directAnim(2)
    }
    this.playerTurn()
    this.updatecardNum()
  }

  chooseFightCArd() {
    this.gameStage = StageType.PlayerAttack

    this.selectFightItem = this.items3.children[this.dragIndex]

    if (!this.selectFightItem) {
      return
    }
    console.log(this.selectFightItem)
    let tmp = getCardById(this.selectFightItem.id)
    let enemyChooseItem = null
    this.items2.children.forEach(v => {
      if (v.highlight.visible) {
        enemyChooseItem = v;
      }
    })
    //console.log()
    console.log(enemyChooseItem)
    let tmp1 = getCardById(enemyChooseItem.id);
    if (tmp1.strenth > tmp.strenth) {
      console.log("敌人攻击")
      this.doattackAnim(enemyChooseItem, this.selectFightItem)
      this.playerWAstCarIds.push(this.selectFightItem.id)
      this.kiiledByIndex = enemyChooseItem.index
      this.getDefeatEvetn(this.selectFightItem.id)

    } else if (tmp1.strenth == tmp.strenth) {
      console.log("一起攻击")
      this.doattackAnim(enemyChooseItem, this.selectFightItem)
      this.doattackAnim(this.selectFightItem, enemyChooseItem)
      this.getDefeatEvetn(this.selectFightItem.id)
      this.getDefeatEvetn(enemyChooseItem.id)
      this.playerWAstCarIds.push(this.selectFightItem.id)
      this.enemyWasterCArdIds.push(enemyChooseItem.id)
    } else {
      console.log("我方攻击攻击")
      this.doattackAnim(this.selectFightItem, enemyChooseItem)
      this.enemyWasterCArdIds.push(enemyChooseItem.id)

      this.getDefeatEvetn(enemyChooseItem.id)
    }
    console.log("xxxxxxxxxxxxxxxxxxxx")
    //this.hideBullet()

  }

  getMonsterFightNum() {
    let num = 0
    this.items3.children.forEach(v => {
      if (v.id > 0) {
        num++
      }
    })
    return num
  }

  doattackAnim(fromItem, toItem, direAttack = false) {

    //let item = this.items1.children[index];
    let offset = fromItem.width / 2
    console.log('from' + offset)
    console.log(fromItem)
    this.bullet.x = fromItem.getGlobalPosition().x + offset;
    this.bullet.y = fromItem.getGlobalPosition().y + offset
    let toX = toItem.getGlobalPosition().x + offset;
    let toY = toItem.getGlobalPosition().y + offset;
    //console.log(this.bullet.x,this.bullet.y,toX,toY)
    //return;
    tween(this.bullet).to({ x: toX, y: toY }, 300, Ease.sineOut).onComplete(() => {
      if (direAttack) {
        this.enemytakeDamage(item.strenth)
      } else {
        setTimeout(() => {
          this.getAttackEffeat(this.selectFightItem)
          toItem.updateId(0)
          if (this.currentTurn = TurnType.Enemy) {
            console.log("玩家允许")
            this.currentTurn = TurnType.Player
            this.playerTurn()
          }
          //this.hideBullet()
          //}
        }, 300);

      }
    })

  }

  hideBullet() {
    this.bullet.x = 9999
    this.bullet.y = 9999
  }


  directAnim(index = 2, isPlayerAttack = true) {
    if (isPlayerAttack) {
      let item = this.items4.children[index];
      let offset = item.width / 2
      this.bullet.x = item.getGlobalPosition().x + offset;
      this.bullet.y = item.getGlobalPosition().y + offset

      let info = getCardById(item.id)
      let damage = info?info.strenth:0
      tween(this.bullet).to({ x: WIDTH / 2, y: 50 }, 300, Ease.sineOut).onComplete(() => {
        this.enemytakeDamage(damage)
      }).wait(100)
    } else {
      let item = this.items2.children[index];
      let offset = item.width / 2
      this.bullet.x = item.getGlobalPosition().x + offset;
      this.bullet.y = item.getGlobalPosition().y + offset
      let info = getCardById(item.id)
      let damage = info?info.strenth:0
      tween(this.bullet).to({ x: WIDTH / 2, y: HEIGHT - 100 }, 300, Ease.sineOut).onComplete(() => {
        this.playertakeDamage(damage)
      }).wait(100)
    }

  }

  playertakeDamage(val:number) {

    this.bullet.x = 9999
    this.bullet.y = 9999
    this.changePlayerHp(-val)
  }

  changePlayerHp(val) {
    this.playerHp += val;
    this.life.text = this.playerHp.toString();

    console.log("造成伤害,剩余" + this.enemyHp)
    if (this.playerHp <= 0) {
      //to('Home', storage.level)
      this.endPanel.visible = true
      this.endText.text = "你输了"

    }
  }

  changePlayerHpTo(val) {
    this.playerHp = val;
    this.life.text = this.playerHp.toString();

   
    if (this.playerHp <= 0) {
      //to('Home', storage.level)
      this.endPanel.visible = true
      this.endText.text = "你输了"

    }
  }

  refreshHpTex() {
    this.life.text = this.playerHp.toString();
    this.life1.text = this.enemyHp.toString();
  }

  enemytakeDamage(val:number) {

    this.bullet.x = 9999
    this.bullet.y = 9999
    this.enemyHp-=val;
    console.log("造成伤害,剩余" + this.enemyHp)
    this.monsterPlaceCard(true)
    if (this.enemyHp <= 0) {
      //to('Home', storage.level)
      this.endPanel.visible = true
      this.endText.text = "胜利"
    }
    this.life1.text = this.enemyHp.toString();
  }

  onDragStart(event: InteractionEvent) {
    event.stopPropagation();
    const obj = event.currentTarget

    if (obj.id) {
      this.dragId = obj.id
      this.dragIndex = obj.index
      if (obj.parent.name != 'items3') {
        this.showDetail(obj)
      } else {
        if (this.gameStage != StageType.PlayerSelectFightCard) {
          console.log('攻击！！！！！！！！！！！！！！！')
          this.selectFightItem = obj
          this.doAttack()
        }

        // this.selectFightItem = this.items3.children[obj.index]
        // this.doattackAnim(this.selectFightItem,)
      }

    }
    if (this.gameStage == StageType.PlayerSelectFightCard) {
      console.log('等待11111111111')
      this.playerTurn()
      this.selectFightItem = this.items3.children.find(x => x.id == this.dragId)
      this.chooseFightCArd(obj.id);
      return;
    }
    if (this.hasDoAction) {
      console.log('xxxxxxx')
      //this.showTip("请结束回合")
      this.detailBox.visible = false
      return
    }

    console.log("drag:" + this.dragId + "-" + this.dragIndex)
  }

  onDrag(event: InteractionEvent) {
    // if (this.hasDoAction) {
    //   //this.showTip("请结束回合")
    //   return
    // }
    const obj = event.currentTarget
    // this.showDetail(obj.id)
    this.isPressing = false;
    this.dragging = 1
    //this.dragging = 1;
    this.dragBox.visible = true
    // if (this.dragging === 1) {
    this.dragBox.x = event.data.global.x
    this.dragBox.y = event.data.global.y
    this.detailBox.visible = false
    //}
  }

  //拖动结束
  onDragEnd(event: InteractionEvent) {
    if (this.hasDoAction) {
      return
    }
    this.dragging = 0
    this.dragBox.visible = false
    this.detailBox.visible = false
    //this.dragId=0
    this.checkHitFightcardArea(this.dragBox.x, this.dragBox.y)
    this.endTuns()
  }

  //是否拖入出牌区域
  checkHitFightcardArea(x, y) {

    let point = new Point(x, y)
    let hit = false
    console.log("draIndex.:" + this.dragIndex)
    if (this.dragIndex == -1 || typeof (this.dragIndex) == "undefined") {
      return;
    }
    console.log(this.items3.children[this.dragIndex])
    let info =  getCardById(this.items4.children[this.dragIndex].id)
    if(this.playerEnergy<info.cost){
      this.showTip("能量不足")
      this.dragBox.visible =false;
      return
    }
    this.items3.children.forEach((m, k) => {
      let item = m as XLevelItem
      if (item.containsPoint(point)) {
        console.log('hasDo')
        console.log("坐标点在矩形区域内id:" + this.dragId);
        this.hasDoAction = true
        this.updatePlayerExtra()
        this.items3.children[k].updateId(this.dragId, true)
        hit = true
      } else {
        //console.log("坐标点不在矩形区域内");
      }
    })
    if (hit && this.dragIndex !== -1) {
      //抽新牌
      if (this.playerStorageCardIs.length <= 0) {
        this.items4.children[this.dragIndex].updateId(0)
        return
      }
      this.playerEnergy-=info.cost
      let cardId = this.playerStorageCardIs.pop()
      console.log("新id" + cardId + '-' + this.dragIndex)
      let tmpId = this.dragId;
      if (cardId != this.items4.children[this.dragIndex].id) {
        //this.hasDoAction = true;
        this.items4.children[this.dragIndex].updateId(cardId)
        let carfInfo = getCardById(tmpId);
        console.log("test")
        console.log(carfInfo)
        if (carfInfo.triggerType == TriggerType.OnScene) {
          this.currentTurn = TurnType.Player
          this.getOneScneEffeat(carfInfo.id)
        }

      }
      this.dragIndex = -1
      
      this.updatecardNum()
    }
  }

  //击败效果
  getDefeatEvetn(id: number, ownnerPlayer: boolean = true) {
    switch (id) {
      case 7:
        this.removeFighatCardRandom(ownnerPlayer)
        break;
      case 12:

        this.controlCard(2)
        break;
      case 26:
        this.stoleHandCard(2, ownnerPlayer)
        break;
    }
  }

  //update为0自己没看，浪费时间
  getAttackEffeat(item: XLevelItem) {
    switch (item.id) {
      case 3:

        if (item.parent.name == "items3") {
          this.directAnim()
        } else {
          this.directAnim(2, false)
        }
        break;
      case 20://[袭击]：击败一只力量≥6的敌方生物。
        console.log("袭击特效:" + item.parent.name)
        this.killMOnsterByCondition(6);
        // this.changePlayerHp(2)
        break;
      case 23:

        this.changePlayerHp(2)
        break;
      case 28:

        this.changePlayerHpTo(1)
        break;
      case 29:

        this.changePlayerHp(2)
        break;
    }
  }

  killMOnsterByCondition(stren: number) {
    for (let i = 0; i < this.items2.children.length; i++) {
      if (this.items2.children[i].id) {
        //console.log("控制id" + this.items2.children[i].id)
        let cardInfo = getCardById(this.items2.children[i].id)
        if (cardInfo && cardInfo.strenth >= stren) {
          let oriId = this.items2.children[i].id;
          this.items2.children[i].updateId(0, true)
          this.showTip("触发攻击特效")
         // this.addNewPlayerFightCardPlayer(oriId)
          console.log("袭击")
          break
        }
      }
    }
  }

  //登场效果
  getOneScneEffeat(id: number) {
    console.log("登场" + id)
    switch (id) {
      case 1:

        this.changePlayerHp(2)
        break;
      case 2:
        // if(this.currentTurn == TurnType.Player){
        for (let i = 0; i < this.items2.children.length; i++) {
          if (this.items2.children[i].id) {
            //console.log("控制id" + this.items2.children[i].id)
            let cardInfo = getCardById(this.items2.children[i].id)
            if (cardInfo && cardInfo.strenth <= 5) {
              let oriId = this.items2.children[i].id;
              this.items2.children[i].updateId(0, true)
              this.addNewPlayerFightCardPlayer(oriId)
              console.log("控制")
              break
            }
          }
        }
        break;
      case 8://[登场]：对手选择并弃掉2张卡。
        for (let i = 0; i < 2; i++) {
          this.enemyStoracardIds.pop()
        }
        this.updatecardNum()

        break;
      case 9://[登场]：将整个弃牌堆抽回手牌。
        let lackNum = 5 - this.playerHandCardIds.length;
        let addNum = 0;
        console.log("丑弃牌" + this.playerHandCardIds.length + '-' + lackNum)
        for (let i = 0; i < this.playerWAstCarIds.length; i++) {
          if (addNum >= lackNum) {

            continue;
          }
          let id = this.playerHandCardIds.pop();
          this.addNewPlayerHandCard(id)
          addNum++;
        }
        this.updatecardNum()

        break;
      case 11://[登场]：对手选择并弃掉2张卡。
        if (this.enemyWasterCArdIds.length >= 1) {
          let id = this.enemyWasterCArdIds.pop()
          console.log("敌人弃牌" + id)
          this.addNewPlayerFightCardPlayer(id);
        }
        //this.updatecardNum()

        break;
      case 13://[登场]：击败敌方所有力量≤4的生物。

        this.removeFighatCard('<=', 4)
        break;
      //this.updatecardNum()
      case 14://[登场]：击败敌方所有力量≤4的生物。
        this.directAnim(2, true)
        break;
      case 17://[登场]：击败敌方所有力量≤4的生物。
        if (this.currentTurn == TurnType.Player) {
          this.removeFighatCard('<=', 4)
        } else {
          this.removeFighatCard('<=', 4, true)
        }
        this.refreshHpTex()
        break;
      case 27://[登场]：[登场]：击败敌方一只力量≥7的生物。

        if (this.currentTurn == TurnType.Player) {
          this.removeFighatCard('>=', 7)
        } else {
          this.removeFighatCard('>=', 7, true)
        }
        this.refreshHpTex()
        break;
      default:
        break;
    }
  }

  controlCard(stoleNum: number) {
    let num = 0
    for (let i = 0; i < this.items2.children.length; i++) {
      if (this.items2.children[i].id) {
        if (num > stoleNum) {
          return;
        }
        console.log("控制id" + this.items2.children[i].id)
        let cardInfo = getCardById(this.items2.children[i].id)
        console.log("控制生物")
        console.log(cardInfo)
        if (cardInfo && cardInfo.strenth <= 5) {
          let oriId = this.items2.children[i].id;
          this.items2.children[i].updateId(0, true)
          this.addNewPlayerFightCardPlayer(oriId)
          console.log("控制")
          break
        }
        num++;
      }

    }
  }

  stoleHandCard(stoleNum: number, ownnerPlayer: boolean = true) {
    console.log("当前回合")
    console.log(this.currentTurn)
    let num = 0;
    if (ownnerPlayer) {
      for (let i = 0; i < this.enmeyHandCardIds.length; i++) {
        if (num > stoleNum) {
          return
        }
        if (this.enmeyHandCardIds[i]) {
          console.log("偷牌id" + i + this.enmeyHandCardIds[i])
          let cardInfo = getCardById(this.enmeyHandCardIds[i])

          let oriId = this.enmeyHandCardIds[i];
          this.enmeyHandCardIds.splice(i, 1)
          this.addNewPlayerHandCard(oriId)
          console.log("偷到了" + num)
          //break
          num++;
        }
      }
      this.updatecardNum()
    } else {
      for (let i = 0; i < this.items4.children.length; i++) {
        if (num >= stoleNum) {
          return
        }
        if (this.items4.children[i].id) {
          console.log("偷牌22222222id" + this.items4.children[i].id)
          let cardInfo = getCardById(this.items4.children[i].id)

          let oriId = this.items4.children[i].id;
          this.items4.children[i].updateId(0, true)
          this.addNewPlayerHandCard(oriId)
          console.log("偷到了")
          break

        }
        num++;

      }
    }

  }

  removeFighatCardRandom(isPlayer: boolean = false) {

    if (!isPlayer) {
      let indexs = this.getPlayerAliveIndexs();
      let ranIndex = getRandomNum(0, indexs.length)
      this.doattackAnim(this.selectFightItem, this.items3.children[indexs[ranIndex]])
      console.log("失败带走" + ranIndex)
    } else {
      let indexs = this.getAliveIndexs();
      let ranIndex = getRandomNum(0, indexs.length)
      console.log("失败带走" + ranIndex)
      this.doattackAnim(this.selectFightItem, this.items2.children[indexs[ranIndex]])
      // for (let i = 0; i < this.items2.children.length; i++) {
      //   if (this.items2.children[i].id) {

      //     console.log("移除id" + this.items2.children[i].id)
      //     //let cardInfo = getCardById(this.items2.children[i].id)
      //     //console.log(cardInfo)
      //     if (cardInfo && cardInfo.strenth <= strenth) {


      //       break
      //     }
      //   }

      // }
    }

  }

  getAliveIndexs() {
    let res = []
    for (let i = 0; i < this.items2.children.length; i++) {
      if (this.items2.children[i].id > 0) {
        res.push(i)
      }
    }
    return res;
  }

  getPlayerAliveIndexs() {
    let res = []
    for (let i = 0; i < this.items3.children.length; i++) {
      if (this.items3.children[i].id > 0) {
        res.push(i)
      }
    }
    return res;
  }

  getEnemyFightNum() {
    let res = 0
    for (let i = 0; i < this.items2.children.length; i++) {
      if (this.items2.children[i].id > 0) {
        res++
      }

    }
    return res;
  }

  removeFighatCard(sign: string = '<=', strenth: number, isPlayer: boolean = false) {
    let items = isPlayer ? this.items3 : this.items2;
    if (isPlayer) {
      for (let i = 0; i < this.items3.children.length; i++) {
        if (this.items3.children[i].id) {
          console.log("移除id" + this.items3.children[i].id)
          let cardInfo = getCardById(this.items3.children[i].id)
          console.log(cardInfo)
          if (cardInfo && cardInfo.strenth <= strenth) {
            if (sign == '<=' && cardInfo.strenth <= strenth) {
              this.items3.children[i].updateId(0, true)
              console.log("移除")
            }
            if (sign == '>=' && cardInfo.strenth >= strenth) {
              this.items3.children[i].updateId(0, true)
              console.log("移除大于")
            }

            break
          }
        }

      }
    } else {
      for (let i = 0; i < this.items2.children.length; i++) {
        if (items.children[i].id) {
          console.log("移除id" + this.items2.children[i].id)
          let cardInfo = getCardById(this.items2.children[i].id)
          console.log(cardInfo)
          if (cardInfo && cardInfo.strenth <= strenth) {
            if (sign == '<=' && cardInfo.strenth <= strenth) {
              this.items2.children[i].updateId(0, true)
              console.log("移除")
            }

            if (sign == '>=' && cardInfo.strenth >= strenth) {
              this.items2.children[i].updateId(0, true)
              console.log("移除大于")
            }

            break
          }
        }

      }
    }

  }

  //抽卡
  addNewPlayerFightCardPlayer(id: number) {

    for (let i = 0; i < this.items3.children.length; i++) {
      console.log("item3-id:" + this.items3.children[i].id)
      if (this.items3.children[i].id <= 0 || !this.items3.children[i].id) {
        console.log("控制怪物22222222222id:" + id)
        this.items3.children[i].updateId(id, true)
        return
      }

    }
  }

  addNewPlayerHandCard(id: number) {

    for (let i = 0; i < this.items4.children.length; i++) {
      if (this.items4.children[i].id <= 0 || !this.items3.children[i].id) {

        this.items4.children[i].updateId(id, true)
        return
      }
    }
  }

  updatePlayerExtra(){
    let  tmpIndex = 0
    let extStr=0
     this.items3.children.forEach((m, i) => {
       //this.items3.children[i].index = tmpIndex
       //this.items3.children[i].belongType = BelongType.Player
       let item = m as XLevelItem
       console.log("额外ip"+extStr)
       extStr =this.getEtracStr(i)
       item.updateStr(extStr)
       tmpIndex++
     })
   }

  updatePlayerHand(){
   let  tmpIndex = 0
    this.items3.children.forEach((m, i) => {
      this.items3.children[i].index = tmpIndex
      this.items3.children[i].belongType = BelongType.Player
      let item = m as XLevelItem
      console.log("额外ip"+this.getEtracStr())
      item.updateId(0, true,this.getEtracStr())
      tmpIndex++
    })
  }

  updateLevelPage() {
    let p = this.currentPage
    let e = storage.level
    // this.btnLeft.visible = (p != 1)
    //this.btnRight.visible = (p * 12 < MAX_LEVEL_LENGTH)
    let tmpIndex = 0
    let id = 0
    this.items4.children.forEach((m, i) => {
      id = this.playerHandCardIds[tmpIndex]
      this.items4.children[i].index = tmpIndex
      let item = m as XLevelItem
      // let id = (p - 1) * 12 + i + 1
      item.updateId(id, true)
      tmpIndex++
    })

    this.updatePlayerHand()
  }

  updateEnemyCardList() {
    this.items2.children.forEach((m, i) => {
      this.items2.children[i].index = i
      this.items3.children[i].belongType = BelongType.Enemy
      let item = m as XLevelItem
      item.updateId(0, true)

    })
  }

}